package com.sora.msmservice.serivce.impl;

import com.sora.msmservice.serivce.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Classname: MsmServiceImpl
 * @Description:
 * @Author: Stonffe
 * @Date: 2023/1/11 21:36
 */
@Service
public class MsmServiceImpl implements MsmService {
    @Resource
    private JavaMailSender sender;
    @Autowired
    private StringRedisTemplate template;
    @Value("${spring.mail.username}")
    private String email;
    @Override
    public void sendVerifyCode(String mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件标题
        message.setSubject("【xxx网站】您的注册码");
        //设置随机数作为验证码
        Random random = new Random();
        int code = random.nextInt(89999) + 10000;//小心机
        //用redis保存验证码
        //提前验证一下，如果发送了多次则删除上一次的验证码，保留最新的验证码
        if (template.opsForValue().get("verify:code:"+mail)!=null){
            template.delete("verify:code:"+mail);
        }
        //设置五分钟过期时间
        template.opsForValue().set("verify:code:"+mail,code+"",5, TimeUnit.MINUTES);
        //邮件内容
        message.setText("您的验证码是："+code+"，五分钟有效，请及时完成注册。若不是本人操作请忽略");
        //谁发送，必须和配置文件中的账号一致
        message.setFrom(email);
        //谁接收
        message.setTo(mail);
        sender.send(message);
    }
}
